#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <memory>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Socket.hpp"


const static int defaultsockfd = -1;
const static int gbacklog = 16;//最大监听数量

using namespace sock_ns;

using io_server_t = std::function<void (socket_ptr sockfd,InetAddr addr)>;

class TcpServer;

//作为参数传入线程中
class ThreadData
{
    public:
    ThreadData(socket_ptr sockfd,InetAddr clientaddr,TcpServer* self)
    :_sockfd(sockfd)
    ,_clientaddr(clientaddr)
    ,_self(self)
    {}

    socket_ptr _sockfd;
    InetAddr _clientaddr;
    TcpServer* _self;//这个可以访问类的函数
};

class TcpServer
{
public:
    TcpServer(int port,io_server_t service)
    :_loacladdr("0",port)//所有的ip都可以接收
    ,_isrunning(false)
    ,_listensock(std::make_unique<TcpSocket>())
    ,_service(service)
    {
        _listensock->BuildListenSocket(_loacladdr);
        
    }
    
    static void* HandlerSock(void* args)
    {
        pthread_detach(pthread_self());//获取调用线程ID，并且detach
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_self->_service(td->_sockfd,td->_clientaddr);//调用服务函数
        close(td->_sockfd->SockFd());
        delete td;
        return nullptr;
    }


    void Loop()
    {
        _isrunning = true;
        //4.接收连接
        while(_isrunning)
        {
            InetAddr peeraddr;
            socket_ptr normalsock = _listensock->Accepter(&peeraddr);
            if(normalsock==nullptr)
                continue;
            
            //创建线程，把收到的信息返回
            pthread_t t;
            ThreadData* ptr = new ThreadData(normalsock,peeraddr,this);
            pthread_create(&t,nullptr,HandlerSock,ptr);//在函数中把线程分离
        }
        _isrunning = false;

    }


    ~TcpServer()
    {}

private:
    std::unique_ptr<TcpSocket> _listensock;
    InetAddr _loacladdr;
    bool _isrunning;
    io_server_t _service;

};